<?php

namespace app\admin\model;

use think\Model;

class GPSCategoryItem extends Model
{
    protected $table = 'gps_category_item';
    protected $autoWriteTimestamp = 'datetime';

    /**
     * 通过分类id删除字段 
     * Author Raven
     * Date 2018-10-07
     * Params [params]
     * @param  integer $category_id [分类id]
     */
    public function removeItemByCatId($category_id = 0)
    {
        return $this->where('fk_category_id', $category_id)->delete();
    }

    /**
     * 通过分类id获取字段数量 
     * Author Raven
     * Date 2018-10-07
     * Params [params]
     * @param  integer $category_id [分类id]
     */
    public function getItemCountByCatId($category_id = 0)
    {
        return $this->where('fk_category_id', $category_id)->count();
    }

    /**
     * 通过分类id获取字段列表 
     * Author Raven
     * Date 2018-10-07
     * Params [params]
     * @param  integer $category_id [分类id]
     */
    public function getItemHexByCatId($category_id = 0)
    {
        return $this->field(['item_name', 'item_hex','item_type'])
            ->where('fk_category_id', $category_id)
            ->order('item_order', 'asc')
            ->select();
    }

    /**
     * 根据index创建数据对象 
     * Author Raven
     * Date 2018-10-07
     * Params [params]
     * @param  integer $category_id [分类id]
     * @param  array   $item_index  [index列表]
     * @param  array   $data        [参数列表]
     */
    public function createDataByItemIndex($category_id = 0,$item_index = [], $data = [])
    {
        $datetime = time();

        $res = [];

        foreach ($item_index as $key => $value) {
            if(isset($data["item_hex_" . $value])){
                $res[] = [
                    'fk_category_id' => $category_id,
                    'item_name' => $data['item_name_' . $value],
                    'item_hex' => $data['item_hex_' . $value],
                    'item_order' => $key,
                    'status' => $data['item_status_' . $value],
                    'create_time' => $datetime,
                    'update_time' => $datetime
                ];
            }
        }

        return $res;
    }

    /**
     * 通过分类id获取字段列表 
     * Author Raven
     * Date 2018-10-08
     * Params [params]
     * @param  integer $category_id [分类id]
     */
    public function getActiveItemHexByCatId($category_id = 0)
    {
        return $this->field(['item_name', 'item_hex','item_type','item_value'])
            ->where('fk_category_id', $category_id)
            ->where('status', 1)
            ->order('item_order', 'asc')
            ->select();
    }
}
